package cn.cymym.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class ComDao<T> {
	private QueryRunner queryRunner = new QueryRunner();
	private Class<T> clazz;

	public ComDao() {
		Type superClass = getClass().getGenericSuperclass();
		if (superClass instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) superClass;
			Type[] typeArgs = parameterizedType.getActualTypeArguments();
			if (typeArgs != null && typeArgs.length > 0) {
				if (typeArgs[0] instanceof Class) {
					clazz = (Class<T>) typeArgs[0];
				}
			}

		}
	}

	/**
	 * 批量处理的方法
	 * 
	 * @param sql
	 * @param args：填充占位符的object[]类型的可变参数
	 */
	public void batch(String sql, Object[]... args) {

	}

	/**
	 * 获取某一字段的值
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public <E> E getForValue(String sql, Object... args) {
		Connection connection = null;
		try {
			connection = jdbcUtil.getConnection();
			return queryRunner.query(connection, sql, new ScalarHandler<>(), args);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jdbcUtil.realse(null, connection);
		}
		return null;

	}

	/**
	 * 返回一个查询的集合
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public List<T> getList(String sql, Object... args) {
		Connection connection = null;
		try {
			connection = jdbcUtil.getConnection();
			return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jdbcUtil.realse(null, connection);
		}
		return null;

	}

	/**
	 * 获取一条语句的查询结果
	 * 
	 * @param sql
	 * @param args
	 * @throws SQLException
	 */
	public T get(String sql, Object... args) throws Exception {
		Connection connection = null;
		try {
			connection = jdbcUtil.getConnection();
			return queryRunner.query(connection, sql, new BeanHandler<>(clazz),args);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jdbcUtil.realse(null, connection);
		}
		return null;
	}

	/**
	 * INSERT UPDATE DELETE
	 * 
	 * @param sql：sql语句
	 * @param args：填充占位符的可变参数
	 */
	public void update(String sql, Object... args) {
		Connection connection = null;
		try {
			connection = jdbcUtil.getConnection();
			queryRunner.update(connection, sql, args);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jdbcUtil.realse(null, connection);
		}
	}

}
